# -*- coding:utf-8 -*-

import httplib

from tornado.web import RequestHandler,HTTPError
import db
import time

class BaseHandler(RequestHandler):
    _first_runing = True
    db = None
    def __init__(self, application, request, **kwargs):
        if BaseHandler._first_runing:
            self._after_prefork()
            BaseHandler._first_runing = False

        self._start_time = time.time()
        super(BaseHandler, self).__init__(application, request, **kwargs)

    def get_current_user(self):
		auth = self.get_secure_cookie("auth")
		if not auth:
			return None
		user = self.db.get("SELECT id,email,password,nick_name,gender,domain,cannotfind,oauth_access_token,oauth_uid,oauth_expires_in FROM users WHERE id=%s",int(auth))
		if not user:
			return None
			
		if time.time() > user["oauth_expires_in"]:
			return None
		return user

    def request_time(self):
        return time.time() - self._start_time

    def _after_prefork(self):
        db.connect()
        BaseHandler.db = db.conn.mysql

class ErrorHandler(BaseHandler):
    def prepare(self):
        super(ErrorHandler, self).prepare()
        self.set_status(404)
        raise HTTPError(404)

